package com.sgb.kjwl.view.ui.activity.self.bid;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentTransaction;
import android.view.View;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPickProjectBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.BidEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.self.BidQuoteListFragment;
import com.sgb.kjwl.viewmodel.self.bid.BidPriceModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

/**
 * 企管业务类型 = 1、租赁经营（机械设备）,2、专业工队（劳务）,3、商铺经营（材料）, 4、工程专项(暂时不使用)
 */
public class BidQuoteActivity extends AppActivity {

    private ActivityPickProjectBinding binding;
    @Inject
    BidPriceModel viewModel;
    private AppFragment[] fragments = new AppFragment[4];
    public AppFragment currentFragment;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    public static void start(Context context, int type) {
        Intent intent = new Intent();
        intent.putExtra("type", type);
        intent.setClass(context, BidQuoteActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pick_project);
        binding.include.titleView.setText("报价查询");
        binding.include.ivBack.setOnClickListener(this);
        binding.setViewModel(viewModel);

//        if (null == fragments[0]) {
//            fragments[0] = BidQuoteListFragment.newInstance(0);
//            getMaterial(false);
//        }
//
//        if (!fragments[0].isAdded()) {
//            getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragments[0]).commit();
//            currentFragment = this.fragments[0];
//        }

        switch (getIntent().getIntExtra("type", 1)) {
            case 3:
                fragments[0] = BidQuoteListFragment.newInstance(0);
                getMaterial(false);
                getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragments[0]).commit();
                break;
            case 1:
                fragments[1] = BidQuoteListFragment.newInstance(1);
                getMachine(false);
                getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragments[1]).commit();
                break;
            case 2:
                fragments[3] = BidQuoteListFragment.newInstance(3);
                getLabor(false);
                getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragments[3]).commit();
                break;
        }

//        TabLayout tab = binding.tab;
//        tab.addTab(tab.newTab().setText("材料分类"));
//        tab.addTab(tab.newTab().setText("机械设备"));
//        tab.addTab(tab.newTab().setText("工程分包"));
//        tab.addTab(tab.newTab().setText("劳务分包"));

//        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                switch (tab.getPosition()) {
//                    case 0:
//                        if (null == fragments[0]) {
//                            fragments[0] = BidQuoteListFragment.newInstance(0);
//                            getMaterial(false);
//                        }
//                        addOrShowFragment(fragments[0]);
//                        break;
//                    case 1:
//                        if (null == fragments[1]) {
//                            fragments[1] = BidQuoteListFragment.newInstance(1);
//                            getMachine(false);
//                        }
//                        addOrShowFragment(fragments[1]);
//                        break;
//                    case 2:
//                        if (null == fragments[2]) {
//                            fragments[2] = BidQuoteListFragment.newInstance(2);
//                            getGc(false);
//                        }
//                        addOrShowFragment(fragments[2]);
//                        break;
//                    case 3:
//                        if (null == fragments[3]) {
//                            fragments[3] = BidQuoteListFragment.newInstance(3);
//                            getLabor(false);
//                        }
//                        addOrShowFragment(fragments[3]);
//                        break;
//                }
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });

    }

    protected void addOrShowFragment(AppFragment fragment) {
        if (currentFragment == fragment) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(R.id.fl_content, fragment).commit();
        } else {
            transaction.hide(currentFragment).show(fragment).commit();
        }
        currentFragment = fragment;
    }

    public void getMaterial(boolean loadMore) {
        viewModel.getMaterial(loadMore);
    }

    public void getMachine(boolean loadMore) {
        viewModel.getMachine(loadMore);
    }

    public void getGc(boolean loadMore) {
        viewModel.getGc(loadMore);
    }

    public void getLabor(boolean loadMore) {
        viewModel.getLabor(loadMore);
    }

    public void showList(List<BidEntity> data) {
        EventBus.getDefault().post(data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    public void emptyList() {
        EventBus.getDefault().post("EMPTY");
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(BidQuoteActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_BID_QUOTE_ACTIVITY_JUMP);
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(getActivity()));
        //开始拉取授权页
        DialogHelper.showProgressDialog(getActivity(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(getActivity(), EventConstant.EVENT_BID_QUOTE_ACTIVITY_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_BID_QUOTE_ACTIVITY_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == R.layout.item_home_pick_type) {
            viewModel.getMaterial(false);
        } else if (event.getMessageTag() == R.layout.item_home_pick_device) {
            viewModel.getMachine(false);
        } else if (event.getMessageTag() == R.layout.item_pick_packers) {
            viewModel.getGc(false);
        } else if (event.getMessageTag() == R.layout.item_home_pick_labour) {
            viewModel.getLabor(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
